<template>
  <view class="address-selector" v-if="visible">
    <!-- 遮罩层 -->
    <view class="mask" @tap="handleCancel"></view>
    
    <!-- 选择器主体 -->
    <view class="selector-container">
      <!-- 标题栏 -->
      <view class="header">
        <text class="cancel-btn" @tap="handleCancel">取消</text>
        <text class="title">选择地址</text>
        <text class="confirm-btn" @tap="handleConfirm">确定</text>
      </view>
      
      <!-- 地址导航 -->
      <view class="nav-tabs">
        <view 
          class="nav-item" 
          :class="{ active: currentLevel === 0 }"
          @tap="switchLevel(0)"
        >
          <text>{{ selectedProvince || '请选择省份' }}</text>
        </view>
        <view 
          class="nav-item" 
          :class="{ active: currentLevel === 1 }"
          @tap="switchLevel(1)"
          v-if="selectedProvince"
        >
          <text>{{ selectedCity || '请选择城市' }}</text>
        </view>
        <view 
          class="nav-item" 
          :class="{ active: currentLevel === 2 }"
          @tap="switchLevel(2)"
          v-if="selectedCity"
        >
          <text>{{ selectedArea || '请选择区县' }}</text>
        </view>
      </view>
      
      <!-- 地址列表 -->
      <scroll-view class="address-list" scroll-y>
        <view 
          class="address-item" 
          v-for="item in currentList" 
          :key="item.code"
          :class="{ active: isSelected(item) }"
          @tap="selectItem(item)"
        >
          <text>{{ item.name }}</text>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script>
import { addressData } from './addressData.js'

export default {
  name: 'AddressSelector',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    defaultAddress: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      currentLevel: 0, // 当前选择级别 0:省份 1:城市 2:区县
      selectedProvince: '',
      selectedCity: '',
      selectedArea: '',
      selectedProvinceCode: '',
      selectedCityCode: '',
      selectedAreaCode: '',
      currentList: [],
      addressData
    }
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.initData()
      }
    }
  },
  methods: {
    // 初始化数据
    initData() {
      console.log('初始化地址选择器数据')
      this.currentLevel = 0
      this.selectedProvince = ''
      this.selectedCity = ''
      this.selectedArea = ''
      this.selectedProvinceCode = ''
      this.selectedCityCode = ''
      this.selectedAreaCode = ''
      this.currentList = this.addressData.provinces
      
      console.log('省份数据：', this.addressData.provinces)
      
      // 如果有默认地址，则设置
      if (this.defaultAddress.province) {
        this.selectedProvince = this.defaultAddress.province
        this.selectedProvinceCode = this.defaultAddress.provinceCode
        this.loadCities()
        if (this.defaultAddress.city) {
          this.selectedCity = this.defaultAddress.city
          this.selectedCityCode = this.defaultAddress.cityCode
          this.loadAreas()
          if (this.defaultAddress.area) {
            this.selectedArea = this.defaultAddress.area
            this.selectedAreaCode = this.defaultAddress.areaCode
          }
        }
      }
    },
    
    // 切换选择级别
    switchLevel(level) {
      this.currentLevel = level
      this.updateCurrentList()
    },
    
    // 更新当前列表
    updateCurrentList() {
      switch (this.currentLevel) {
        case 0:
          this.currentList = this.addressData.provinces
          break
        case 1:
          this.currentList = this.getCitiesByProvince(this.selectedProvinceCode)
          break
        case 2:
          this.currentList = this.getAreasByCity(this.selectedCityCode)
          break
      }
    },
    
    // 选择地址项
    selectItem(item) {
      switch (this.currentLevel) {
        case 0:
          this.selectProvince(item)
          break
        case 1:
          this.selectCity(item)
          break
        case 2:
          this.selectArea(item)
          break
      }
    },
    
    // 选择省份
    selectProvince(item) {
      console.log('选择省份：', item)
      this.selectedProvince = item.name
      this.selectedProvinceCode = item.code
      this.selectedCity = ''
      this.selectedArea = ''
      this.selectedCityCode = ''
      this.selectedAreaCode = ''
      
      this.currentLevel = 1
      this.loadCities()
    },
    
    // 选择城市
    selectCity(item) {
      console.log('选择城市：', item)
      this.selectedCity = item.name
      this.selectedCityCode = item.code
      this.selectedArea = ''
      this.selectedAreaCode = ''
      
      this.currentLevel = 2
      this.loadAreas()
    },
    
    // 选择区县
    selectArea(item) {
      console.log('选择区县：', item)
      this.selectedArea = item.name
      this.selectedAreaCode = item.code
    },
    
    // 加载城市列表
    loadCities() {
      this.currentList = this.getCitiesByProvince(this.selectedProvinceCode)
    },
    
    // 加载区县列表
    loadAreas() {
      this.currentList = this.getAreasByCity(this.selectedCityCode)
    },
    
    // 根据省份获取城市
    getCitiesByProvince(provinceCode) {
      const cities = this.addressData.cities[provinceCode] || []
      return cities.map(city => ({
        code: city.code,
        name: city.name
      }))
    },
    
    // 根据城市获取区县
    getAreasByCity(cityCode) {
      const areas = this.addressData.areas[cityCode] || []
      return areas.map(area => ({
        code: area.code,
        name: area.name
      }))
    },
    
    // 判断是否选中
    isSelected(item) {
      switch (this.currentLevel) {
        case 0:
          return this.selectedProvinceCode === item.code
        case 1:
          return this.selectedCityCode === item.code
        case 2:
          return this.selectedAreaCode === item.code
        default:
          return false
      }
    },
    
    // 取消选择
    handleCancel() {
      this.$emit('cancel')
    },
    
    // 确认选择
    handleConfirm() {
      console.log('确认选择，当前状态：', {
        selectedProvince: this.selectedProvince,
        selectedCity: this.selectedCity,
        selectedArea: this.selectedArea,
        selectedProvinceCode: this.selectedProvinceCode,
        selectedCityCode: this.selectedCityCode,
        selectedAreaCode: this.selectedAreaCode
      })
      
      if (!this.selectedProvince) {
        uni.showToast({
          title: '请选择省份',
          icon: 'none'
        })
        return
      }
      
      if (!this.selectedCity) {
        uni.showToast({
          title: '请选择城市',
          icon: 'none'
        })
        return
      }
      
      if (!this.selectedArea) {
        uni.showToast({
          title: '请选择区县',
          icon: 'none'
        })
        return
      }
      
      const result = {
        province: this.selectedProvince,
        city: this.selectedCity,
        area: this.selectedArea,
        provinceCode: this.selectedProvinceCode,
        cityCode: this.selectedCityCode,
        areaCode: this.selectedAreaCode,
        fullText: `${this.selectedProvince}${this.selectedCity}${this.selectedArea}`
      }
      
      console.log('准备发送确认结果：', result)
      this.$emit('confirm', result)
    }
  }
}
</script>

<style scoped>
.address-selector {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;
}

.mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.selector-container {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #ffffff;
  border-radius: 20rpx 20rpx 0 0;
  max-height: 80vh;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx 40rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.cancel-btn, .confirm-btn {
  font-size: 30rpx;
  color: #1677ff;
}

.title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333333;
}

.nav-tabs {
  display: flex;
  padding: 0 40rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.nav-item {
  flex: 1;
  padding: 30rpx 0;
  text-align: center;
  position: relative;
}

.nav-item text {
  font-size: 28rpx;
  color: #666666;
}

.nav-item.active text {
  color: #1677ff;
  font-weight: 600;
}

.nav-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60rpx;
  height: 4rpx;
  background-color: #1677ff;
  border-radius: 2rpx;
}

.address-list {
  height: 500rpx;
  padding: 0 40rpx;
}

.address-item {
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  display: flex;
  align-items: center;
}

.address-item:last-child {
  border-bottom: none;
}

.address-item text {
  font-size: 30rpx;
  color: #333333;
}

.address-item.active text {
  color: #1677ff;
  font-weight: 600;
}

.address-item.active::before {
  content: '✓';
  margin-right: 20rpx;
  color: #1677ff;
  font-weight: bold;
}
</style>

